package com.china08.yxyapi.service.manage.tec.teaching.homework.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.china08.yxyapi.entity.db.res.YxyResBookContentsKnoledges;
import com.china08.yxyapi.entity.es.ElasticYxyYxyQuesResource;
import com.china08.yxyapi.entity.mg.homework.HomeWorkQuesUsed;
import com.china08.yxyapi.entity.mg.homework.HomeworkQuesFavorite;
import com.china08.yxyapi.entity.mg.homework.HomeworkQuesGroupRelQues;
import com.china08.yxyapi.entity.mg.res.YxyResQues;
import com.china08.yxyapi.model.question.HomeworkQuesGroupRelQuesModel;
import com.china08.yxyapi.repository.db.YxyResBookContentsKnoledgesRepository;
import com.china08.yxyapi.repository.db.YxyResBookContentsRepository;
import com.china08.yxyapi.repository.es.ElasticYxyYxyQuesResourceRespository;
import com.china08.yxyapi.repository.mg.YxyResQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkQuesFavoriteRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkQuesUsedRepository;
import com.china08.yxyapi.service.manage.tec.teaching.homework.ElasticQuesService;
import com.china08.yxyapi.service.manage.tec.teaching.homework.HomeworkQuestionService;
import com.china08.yxyapi.util.EsQuestionUpdateUtil;
import com.china08.yxyapi.util.MongodbUtil;
import com.china08.yxyapi.util.YxyResUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;

@Service
public class HomeworkQuestionServiceImpl implements HomeworkQuestionService {

    @Autowired
    private ElasticQuesService elasticQuesService;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private ElasticYxyYxyQuesResourceRespository elasticYxyYxyQuesResourceRespository;

    @Autowired
    private HomeworkQuesFavoriteRepository homeworkQuesFavoriteRepository;

    @Autowired
    private HomeworkQuesUsedRepository homeWorkQuesUsedRepository;

    @Autowired
    private YxyResBookContentsKnoledgesRepository yxyResBookContentsKnoledgesRepository;

    @Autowired
    private YxyResBookContentsRepository yxyResBookContentsRepository;

    @Autowired
    private YxyResUtil yxyResUtil;

    @Autowired
    private YxyResQuesRepository yxyResQuesRepository;

    @Autowired
    private MongoTemplate mt;

    @Override
    public BoolQueryBuilder get(BoolQueryBuilder boolQueryBuilder, String level, String type, String use) {
        // 只查询未删除的
        TermQueryBuilder deleteBuilder = new TermQueryBuilder("deleteFlag", "0");
        boolQueryBuilder.must(deleteBuilder);

        // 只能查询不是私人的
        TermQueryBuilder viewScopeBuilder = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(viewScopeBuilder);
        //
        if (StringUtils.isNotBlank(level) && !StringUtils.equals("all", level)) {
            TermQueryBuilder builder = new TermQueryBuilder("difficultyLevel", level);
            boolQueryBuilder.must(builder);
        }
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            if (StringUtils.equals("6", type)) {
                List<String> notquesType = new ArrayList<String>();
                notquesType.add("1");
                notquesType.add("2");
                notquesType.add("8");
                TermsQueryBuilder builder = new TermsQueryBuilder("questionType", notquesType);
                boolQueryBuilder.mustNot(builder);
            } else {
                TermQueryBuilder builder = new TermQueryBuilder("questionType", type);
                boolQueryBuilder.must(builder);
            }
        } else {
            //
            // 目前只有 单选 和多选
            // BoolQueryBuilder typeOr = new BoolQueryBuilder();
            // TermQueryBuilder builder1 = new TermQueryBuilder("questionType",
            // "1");
            // TermQueryBuilder builder8 = new TermQueryBuilder("questionType",
            // "8");
            // typeOr.should(builder1);
            // typeOr.should(builder8);
            // boolQueryBuilder.must(typeOr);
        }
        if (StringUtils.isNotBlank(use) && !StringUtils.equals("all", use)) {
            List<String> ids = new ArrayList<String>();
            if (StringUtils.equals("0", use)) {
                // 未使用过
            } else {
                // 使用过
            }
        }

        return boolQueryBuilder;
    }

    /**
     * 查询page
     * 
     * @param boolQueryBuilder
     * @param pageable
     * @return
     */
    private Page<ElasticYxyYxyQuesResource> getPage(BoolQueryBuilder boolQueryBuilder, Pageable pageable) {
        SearchQuery query = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(boolQueryBuilder).build();
        Page<ElasticYxyYxyQuesResource> page = elasticsearchTemplate.queryForPage(query,
                ElasticYxyYxyQuesResource.class);
        return page;
    }

    private List<ElasticYxyYxyQuesResource> getList(BoolQueryBuilder boolQueryBuilder) {
        SearchQuery query = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).build();
        return elasticsearchTemplate.queryForList(query, ElasticYxyYxyQuesResource.class);
    }

    @Override
    public boolean checkCollectionQuestion(String userId, String quesId) {
        long count = homeworkQuesFavoriteRepository.countByTeacherIdAndQuesId(userId, quesId);
        return count > 0;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> collectionfindByMy(String phase, String subject, String userId, String level,
            String type, Pageable pageable) {

        Page<HomeworkQuesFavorite> favoritePage = null;
        if (StringUtils.isNotBlank(level) && !StringUtils.equals("all", level) && StringUtils.isNotBlank(type)
                && !StringUtils.equals("all", type)) {
            favoritePage = homeworkQuesFavoriteRepository
                    .findByTeacherIdAndStageAndSubjectAndDifficultyLevelAndQuesType(userId, phase, subject,
                            Integer.parseInt(level), type, pageable);
        } else if (StringUtils.isNotBlank(level) && !StringUtils.equals("all", level)) {
            favoritePage = homeworkQuesFavoriteRepository.findByTeacherIdAndStageAndSubjectAndDifficultyLevel(userId,
                    phase, subject, Integer.parseInt(level), pageable);
        } else if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            if (StringUtils.equals("6", type)) {
                List<String> ninType = new ArrayList<String>();
                ninType.add("1");
                ninType.add("2");
                ninType.add("8");
                favoritePage = homeworkQuesFavoriteRepository.findByTeacherIdAndStageAndSubjectAndQuesTypeNotIn(userId,
                        phase, subject, ninType, pageable);
            } else {
                favoritePage = homeworkQuesFavoriteRepository.findByTeacherIdAndStageAndSubjectAndQuesType(userId,
                        phase, subject, type, pageable);
            }
        } else {
            favoritePage = homeworkQuesFavoriteRepository.findByTeacherIdAndStageAndSubject(userId, phase, subject,
                    pageable);
        }
        long countFavorite = favoritePage.getTotalElements();
        List<String> quesIds = favoritePage.getContent().stream().map(x -> x.getQuesId()).collect(Collectors.toList());
        List<ElasticYxyYxyQuesResource> list = null;
        if (quesIds.size() > 0) {
            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
            boolQueryBuilder = get(boolQueryBuilder, null, null, null);
            TermsQueryBuilder builder = new TermsQueryBuilder("id", quesIds);
            boolQueryBuilder.must(builder);
            list = getList(boolQueryBuilder);
        } else {
            list = new ArrayList<ElasticYxyYxyQuesResource>();
        }
        Page<ElasticYxyYxyQuesResource> respPage = new PageImpl<>(list, pageable, countFavorite);
        return respPage;
    }

    @Override
    public void collectionQuestion(String userId, String schoolId, String quesId) {
        ElasticYxyYxyQuesResource elasticYxyYxyQuesResource = elasticYxyYxyQuesResourceRespository.findById(quesId);
        Assert.notNull(elasticYxyYxyQuesResource, "试题不存在请刷新页面");
        HomeworkQuesFavorite favorite = homeworkQuesFavoriteRepository.findByQuesIdAndTeacherId(quesId, userId);
        // Assert.isNull(favorite, "您已经收藏过了，请刷新页面");
        if (favorite == null) {
            favorite = new HomeworkQuesFavorite();
            favorite.setCreatedBy(userId);
            favorite.setLastModifiedBy(userId);
            favorite.setTeacherId(userId);
            favorite.setSchoolId(schoolId);
            favorite.setStage(elasticYxyYxyQuesResource.getPhase());
            favorite.setSubject(elasticYxyYxyQuesResource.getSubject());
            favorite.setQuesId(elasticYxyYxyQuesResource.getId());
            List<Integer> knowIds = elasticYxyYxyQuesResource.getKnowledgeIds();
            String know = "";
            if (knowIds != null && knowIds.size() > 0) {
                know = StringUtils.join(knowIds, ",");
            }
            favorite.setKnowIds(know);
            favorite.setQuesType(elasticYxyYxyQuesResource.getQuestionType());
            favorite.setDifficultyLevel(Integer.parseInt(elasticYxyYxyQuesResource.getDifficultyLevel()));
            homeworkQuesFavoriteRepository.save(favorite);
            YxyResQues yxyResQues = yxyResQuesRepository.findById(quesId);
            if (yxyResQues != null) {
                yxyResQues.setHomeworkFavoriteCount(homeworkQuesFavoriteRepository.countByQuesId(quesId));
                yxyResQues.setSycEsFlag(0);
                yxyResQuesRepository.save(yxyResQues);
                EsQuestionUpdateUtil.updateEsQuestion(quesId);
            }
        }

    }

    @Override
    public void collectionRemoveQuestion(String userId, String quesId) {
        HomeworkQuesFavorite favorite = homeworkQuesFavoriteRepository.findByQuesIdAndTeacherId(quesId, userId);
        // Assert.notNull(favorite, "您并没有收藏试题，请刷新页面");
        if (favorite != null) {
            homeworkQuesFavoriteRepository.delete(favorite);
            YxyResQues yxyResQues = yxyResQuesRepository.findById(quesId);
            if (yxyResQues != null) {
                yxyResQues.setHomeworkFavoriteCount(homeworkQuesFavoriteRepository.countByQuesId(quesId));
                yxyResQues.setSycEsFlag(0);
                yxyResQuesRepository.save(yxyResQues);
                EsQuestionUpdateUtil.updateEsQuestion(quesId);
            }
        }
    }

    @Override
    public Long countQuestionUse(String quesId) {
        HomeWorkQuesUsed homeWorkQuesUsed = homeWorkQuesUsedRepository.findByQuesId(quesId);
        return homeWorkQuesUsed != null ? homeWorkQuesUsed.getUsedCount() : 0;
    }

    @Override
    public double questionDateTime(String quesId) {
        ElasticYxyYxyQuesResource elasticYxyYxyQuesResource = elasticQuesService.findByEsQuesId(quesId);
        Assert.notNull(elasticYxyYxyQuesResource, "试题未找到请刷新页面");
        String quesType = elasticYxyYxyQuesResource.getQuestionType();
        String queslevel = elasticYxyYxyQuesResource.getDifficultyLevel();
        double dateTime = 0.0;
        // 简单
        if (StringUtils.equals("1", queslevel)) {
            // 单选
            if (StringUtils.equals("1", quesType)) {
                dateTime = 1;
            }
            // 多选
            else if (StringUtils.equals("8", quesType)) {
                dateTime = 1.5;
            }
            // 填空
            else if (StringUtils.equals("2", quesType)) {
                dateTime = 1;
            }
            // 解答
            else {
                dateTime = 3;
            }
        }
        // 中等
        else if (StringUtils.equals("2", queslevel)) {
            // 单选
            if (StringUtils.equals("1", quesType)) {
                dateTime = 2;
            }
            // 多选
            else if (StringUtils.equals("8", quesType)) {
                dateTime = 2.5;
            }
            // 填空
            else if (StringUtils.equals("2", quesType)) {
                dateTime = 2;
            }
            // 解答
            else {
                dateTime = 5;
            }
        }
        // 困难
        else if (StringUtils.equals("3", queslevel)) {
            // 单选
            if (StringUtils.equals("1", quesType)) {
                dateTime = 4;
            }
            // 多选
            else if (StringUtils.equals("8", quesType)) {
                dateTime = 4.5;
            }
            // 填空
            else if (StringUtils.equals("2", quesType)) {
                dateTime = 3;
            }
            // 解答
            else {
                dateTime = 8;
            }
        }
        return dateTime;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> questionFindByBookcontentAndLevelAndTypeAndUse(String bookcontent,
            String level, String type, String use, String userId, String bookId, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 基本查询
        boolQueryBuilder = get(boolQueryBuilder, level, type, use);
        // 目录
        if (StringUtils.isNotBlank(bookcontent) && !StringUtils.equals("all", bookcontent)) {
            // 目录查询
            boolQueryBuilder = questionFindByBookcontent(boolQueryBuilder, bookcontent);
        } else {
            List<String> bookContent = yxyResBookContentsRepository.findIdByBookId(bookId);
            if (bookContent.size() > 0) {
                List<YxyResBookContentsKnoledges> bookContentsKnoledges = yxyResBookContentsKnoledgesRepository
                        .findByBookContentIdIn(bookContent);
                if (bookContentsKnoledges.size() > 0) {
                    List<Integer> knowIds = bookContentsKnoledges.stream().map(x -> x.getKnowledgeId())
                            .collect(Collectors.toList());
                    TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", knowIds);
                    boolQueryBuilder.must(builder);
                } else {
                    TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", new ArrayList<>());
                    boolQueryBuilder.must(builder);
                }
            } else {
                TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", new ArrayList<>());
                boolQueryBuilder.must(builder);
            }
        }
        Page<ElasticYxyYxyQuesResource> page = getPage(boolQueryBuilder, pageable);
        return page;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> questionFindByKnowAndLevelAndTypeAndUse(String know, String level,
            String type, String use, String userId, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (StringUtils.isNotBlank(know) && !StringUtils.equals("all", know)) {
            TermQueryBuilder builder = new TermQueryBuilder("knowFullIds", Integer.parseInt(know));
            boolQueryBuilder.must(builder);
        }
        // 基本查询
        boolQueryBuilder = get(boolQueryBuilder, level, type, use);
        Page<ElasticYxyYxyQuesResource> page = getPage(boolQueryBuilder, pageable);
        return page;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> questionFindByMyGroupId(String schoolId, String userId, String groupId,
            String level, String type, String phase, String subject, Pageable pageable) {
        DBCollection collection = mt.getCollection(mt.getCollectionName(HomeworkQuesGroupRelQues.class));
        BasicDBObject dbObject = new BasicDBObject();
        dbObject.put("school_id", schoolId);
        dbObject.put("teacher_id", userId);
        dbObject.put("group_id", groupId);
        dbObject.put("stage", phase);
        dbObject.put("subject", subject);
        if (StringUtils.isNotBlank(level) && !StringUtils.equals("all", level)) {
            dbObject.put("defficulty_level", Integer.parseInt(level));
        }
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            if (StringUtils.equals("6", type)) {
                List<String> ninTypeList = new ArrayList<String>();
                ninTypeList.add("1");
                ninTypeList.add("2");
                ninTypeList.add("8");
                BasicDBObject ninType = new BasicDBObject("$nin", ninTypeList);
                dbObject.put("ques_type", ninType);
            } else {
                dbObject.put("ques_type", type);
            }
        }
        Page<HomeworkQuesGroupRelQuesModel> groupRelQuesModelPage = MongodbUtil.getPage(collection, dbObject, pageable,
                HomeworkQuesGroupRelQuesModel.class);
        List<String> quesIds = groupRelQuesModelPage.getContent().stream().map(x -> x.getQues_id())
                .collect(Collectors.toList());
        List<ElasticYxyYxyQuesResource> respList = new ArrayList<ElasticYxyYxyQuesResource>();
        for (String string : quesIds) {
            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
            TermsQueryBuilder builder = new TermsQueryBuilder("id", string);
            boolQueryBuilder.must(builder);
            TermsQueryBuilder delBuilder = new TermsQueryBuilder("deleteFlag", "0");
            boolQueryBuilder.must(delBuilder);
            List<ElasticYxyYxyQuesResource> searList = getList(boolQueryBuilder);
            if (searList.size() == 0) {
                ElasticYxyYxyQuesResource elasticYxyYxyQuesResource = new ElasticYxyYxyQuesResource();
                elasticYxyYxyQuesResource.setId(string);
            } else {
                respList.addAll(searList);
            }
        }
        Page<ElasticYxyYxyQuesResource> respPage = new PageImpl<ElasticYxyYxyQuesResource>(respList, pageable,
                groupRelQuesModelPage.getTotalElements());
        return respPage;
    }

    @Override
    public BoolQueryBuilder questionFindByBookcontent(BoolQueryBuilder boolQueryBuilder, String bookcontent) {
        // 找到这个目录下的所有子目录
        List<String> bookcontentList = yxyResUtil.findTocByTocParent(bookcontent);
        List<YxyResBookContentsKnoledges> bookContentsKnoledges = yxyResBookContentsKnoledgesRepository
                .findByBookContentIdIn(bookcontentList);
        if (bookContentsKnoledges.size() > 0) {
            List<Integer> knowIds = bookContentsKnoledges.stream().map(x -> x.getKnowledgeId())
                    .collect(Collectors.toList());
            TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", knowIds);
            boolQueryBuilder.must(builder);
        } else {
            List<Integer> knoids = new ArrayList<Integer>();
            TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", knoids);
            boolQueryBuilder.must(builder);
        }
        return boolQueryBuilder;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> findMyUpload(String phase, String subject, String userId, String level,
            String type, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 基本查询
        // boolQueryBuilder = get(boolQueryBuilder, level, type, null);

        TermsQueryBuilder builderUserId = new TermsQueryBuilder("createdBy", userId);
        boolQueryBuilder.must(builderUserId);
        Page<ElasticYxyYxyQuesResource> page = getPage(boolQueryBuilder, pageable);
        return page;
    }

}
